package com.heu.blood.statistic.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heu.blood.common.utils.PageUtils;
import com.heu.blood.common.utils.Query;
import com.heu.blood.statistic.dao.BloodInventoryDao;
import com.heu.blood.statistic.entity.*;
import com.heu.blood.statistic.service.BloodInventoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
 * @author bearH
 * @date 2023-09-08 18:24
 */
@Service("bloodInventoryService")
public class BloodInventoryServiceImpl extends ServiceImpl<BloodInventoryDao, BloodInventory> implements BloodInventoryService {
    @Autowired
    BloodInventoryDao bloodInventoryDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
//        存放最终的结果
//        Map<String, ArrayList<Object>> rs = new HashMap<>();
//        Map<String, BloodInventoryVo> rs2 = new HashMap<>();
//        BloodInventoryVo bloodVo = new BloodInventoryVo();
//        Query<BloodInventory> query = new Query<>();
//        IPage<BloodInventory> page = query.getPage(params);
//        IPage<BloodInventory> bloodInventoryIPage = bloodInventoryDao.queryPage(page,params);
//        List<BloodInventory> records = bloodInventoryIPage.getRecords();
//        for (BloodInventory record : records) {
//            if (!rs.containsKey(record.getBloodGroup())) {
//                rs.put(record.getBloodGroup(), new ArrayList<>());
//            }
//            rs.get(record.getBloodGroup()).add(record);
//        }
//
//
//
//        System.out.println(rs);
        Query<BloodInventory> query = new Query<>();
        IPage<BloodInventory> page = query.getPage(params);
        IPage<BloodInventory> bloodInventoryIPage = bloodInventoryDao.queryPage(page,params);
        List<BloodInventory> records = bloodInventoryIPage.getRecords();
        Map<String, BloodInventoryVo> rs2 = new HashMap<>();

        for (BloodInventory record : records) {
            String group = record.getBloodGroup();
            if (!rs2.containsKey(group)) {
                BloodInventoryVo newBloodInventoryVo = new BloodInventoryVo();
                newBloodInventoryVo.setBloodGroup(group);
                newBloodInventoryVo.setList(new ArrayList<>());
                rs2.put(group, newBloodInventoryVo);
            }

            BloodInventoryVo currentBloodInventoryVo = rs2.get(group);
            currentBloodInventoryVo.getList().add(record);  // 将记录添加到当前血型的列表中

            currentBloodInventoryVo.setTotalCountA(currentBloodInventoryVo.getTotalCountA() + record.getCountA());
            currentBloodInventoryVo.setTotalCountB(currentBloodInventoryVo.getTotalCountB() + record.getCountB());
            currentBloodInventoryVo.setTotalCountO(currentBloodInventoryVo.getTotalCountO() + record.getCountO());
        }

        System.out.println(rs2);

        List<BloodInventoryVo> bloodInventoryVoList = new ArrayList<>(rs2.values());
        PageUtils pageUtils = new PageUtils(bloodInventoryVoList, (int) bloodInventoryIPage.getTotal(), (int) bloodInventoryIPage.getSize(), (int) bloodInventoryIPage.getCurrent());

        return pageUtils;
    }

    @Override
    public BloodStorageData queryStorage() {
        List<BloodStorageShowVo> bloodStorageShowVos = bloodInventoryDao.queryStorage();
        BloodStorageData bloodStorageData = new BloodStorageData();
        // 使用 Map 来存储结果：key 为 blood_type，value 为 List<EchartItem>
        Map<String, Map<String, BigDecimal>> aggregatedData = new HashMap<>();
        Map<String, BigDecimal> aggregatedAboBloodTypes = new HashMap<>();
        Map<String, BigDecimal> aggregatedRhBloodTypes = new HashMap<>();
        for (BloodStorageShowVo vo : bloodStorageShowVos) {
            String bloodType = vo.getBloodType();         // PLATELET_CONCENTRATE, WHOLE_BLOOD 等
            String aboBloodType = vo.getAboBloodType();   // A, B, O 等
            String rhBloodType = vo.getRhBloodType();    // +, -
            BigDecimal bloodCount = vo.getBloodCount();   // blood_count 的值 (BigDecimal)

            // 聚合数据：按 blood_type 和 abo_blood_type 分类加和
            aggregatedData
                    .computeIfAbsent(bloodType, k -> new HashMap<>())
                    .merge(aboBloodType, bloodCount, (existingCount, newCount) -> existingCount.add(newCount));
            aggregatedAboBloodTypes.merge(aboBloodType, bloodCount, (existingCount, newCount) -> existingCount.add(newCount));
            // 按照 Rh 血型聚合血液计数
            aggregatedRhBloodTypes.merge(rhBloodType, bloodCount, (existingCount, newCount) -> existingCount.add(newCount));
        }
        Map<String, List<EchartItem>> result = new HashMap<>();
        List<String> Xlist = new ArrayList<>();
        List<BigDecimal> Ylist = new ArrayList<>();
        for (Map.Entry<String, Map<String, BigDecimal>> entry : aggregatedData.entrySet()) {
            String bloodType = entry.getKey();
            List<EchartItem> items = entry.getValue().entrySet().stream()
                    .map(e -> new EchartItem(e.getKey(), e.getValue()))
                    .collect(Collectors.toList());
            // 把血型添加到 Xlist 中
            Xlist.add(bloodType);

            // 把对应的血液数量添加到 Ylist 中
            BigDecimal totalBloodCount = entry.getValue().values().stream()
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            Ylist.add(totalBloodCount);
            result.put(bloodType, items);
        }
        List<EchartItem> ABOList = new ArrayList<>();
        for (Map.Entry<String, BigDecimal> entry : aggregatedAboBloodTypes.entrySet()) {
            EchartItem item = new EchartItem();
            item.setName(entry.getKey()); // ABO 血型（A、B、O等）
            item.setValue(entry.getValue());  // 加和后的血液计数
            ABOList.add(item);
        }
        List<EchartItem> RHList = new ArrayList<>();
        for (Map.Entry<String, BigDecimal> entry : aggregatedRhBloodTypes.entrySet()) {
            EchartItem item = new EchartItem();
            item.setName(entry.getKey()); // Rh 血型（+、-）
            item.setValue(entry.getValue());  // 加和后的血液计数
            RHList.add(item);
        }
        bloodStorageData.setResult(result);
        bloodStorageData.setABOList(ABOList);
        bloodStorageData.setRHList(RHList);
        bloodStorageData.setXlist(Xlist);
        bloodStorageData.setYlist(Ylist);

        return bloodStorageData;
    }
}
